package megrez.keycloak.providers.mail;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.keycloak.email.EmailException;
import org.keycloak.email.EmailSenderProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserModel;

import lombok.extern.slf4j.Slf4j;
import megrez.common.core.bean.MailMessage;
import megrez.keycloak.providers.mqtt.MqttService;
import megrez.keycloak.providers.mqtt.MqttUtils;

/**
 * 邮件发送提供者实现
 *  
 * @author Lucky Yang
 * @since 17.0.1
 */
@Slf4j
public class MqttEmailSenderProvider implements EmailSenderProvider {
    private final KeycloakSession session;

    public MqttEmailSenderProvider(KeycloakSession session) {
        this.session = session;
    }

    @Override
    public void close() {
        // 不需要实现
    }

    @Override
    public void send(Map<String, String> config, UserModel user, String subject, String textBody, String htmlBody)
            throws EmailException {
        final Locale locale = session.getContext().resolveLocale(user);

        try {
            final MailMessage message = MailUtils.buildMailMessage(locale, user.getEmail(), user.getFirstName(), user.getLastName(), subject, textBody, htmlBody);
            sendToMqtt(session, message);
        } catch (Exception e) {
            throw new EmailException(e);
        }

    }

    private void sendToMqtt(KeycloakSession session, MailMessage message) {
		final String topic = MailUtils.getMqttTopic(session.getContext().getRealm().getId());
		MqttService client = session.getProvider(MqttService.class);

		try {
			if (!client.isConnected()) {
				client.reconnect();
			}
			client.publish(topic, MqttUtils.buildJsonMqttMessage(message, 2, true));
		} catch (MqttException | IOException e) {
			log.error("Send message to MQTT server exception", e);
		}

	}
}
